# coding:utf-8
from odoo import models, fields, api, _
import dateutil.parser
import odoo.addons.decimal_precision as dp


class OLPurchaseOrderLineExtend(models.Model):
    _inherit = ["purchase.order.line", "stock.view.quant.mixin"]
    _name = "purchase.order.line"
    _order = "date_order desc, id desc"

    product_purchase_limit_control = fields.Boolean(string="Template Purchase Limit Control",
                                                    related="product_id.product_purchase_limit_control", readonly=True)
    product_purchase_limit = fields.Float(string="Template Limit",
                                          related="product_id.product_purchase_limit", readonly=True)

    note = fields.Text(string="Note")
    request_order_line_id = fields.Many2one("purchase.request.order.line", string="Purchase Request Line")
    price_unit_read = fields.Float(string='Unit Price', readonly=True,
                                   digits=dp.get_precision('Product Price'), related='price_unit')
    pr_line_id = fields.Many2one('purchase.request.order.line', string='PR Line')
    request_order_id = fields.Many2one("purchase.request.order", related="pr_line_id.order_id",
                                       string="Request Order")
    product_code = fields.Char('Product Code')
    product_name = fields.Char('Product Name')
    qty_returned = fields.Float(compute='_compute_qty_returned', string="Returned Qty",
                                digits=dp.get_precision('Product Unit of Measure'), store=False)
    partner_id = fields.Many2one('res.partner', string="Partner", related="order_id.partner_id")
    requisition_memo = fields.Text("Requisition Memo")
    seller_price = fields.Float(u'价格表金额', compute='_get_supplierinfo_price', store=False, readonly=True, digits=dp.get_precision('Product Price'))

    @api.model
    def _get_order_date(self):
        for line in self:
            line.date_order = dateutil.parser.parse(line.datetime_order).date()

    datetime_order = fields.Datetime(string='Order Date', related='order_id.date_order')
    date_order = fields.Date(string='Order Date', compute=_get_order_date, readonly=True)

    @api.onchange('product_id', 'partner_id')
    def _onchange_supplierinfo(self):
        if not self.product_id:
            return

        seller = self.product_id._select_seller(
            partner_id=self.partner_id,
            quantity=self.product_qty,
            date=self.order_id.date_order and self.order_id.date_order[:10],
            uom_id=self.product_uom)

        if not seller:
            return

        self.product_code = seller.product_code
        self.product_name = seller.product_name

    def _get_supplierinfo_price(self):
        for line in self:
            if not line.product_id:
                continue

            seller = line.product_id._select_seller(
                partner_id=line.partner_id,
                quantity=line.product_qty,
                date=line.order_id.date_order and line.order_id.date_order[:10],
                uom_id=line.product_uom)

            if not seller:
                continue

            line.seller_price = seller.price

    @api.multi
    def action_query_history(self):
        self.ensure_one()
        ir_model_data = self.env['ir.model.data']
        # TODO if set top N, could search result first, and then using the id set to final domain
        try:
            compose_form_id = ir_model_data.get_object_reference('purchase_order_extend', 'ol_purchase_order_history')[1]
        except ValueError:
            compose_form_id = False
        ctx = dict()
        ctx.update({
            'default_model': 'purchase.order.line',
            'purchase_order_line_ids': self.ids[0]
        })
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'tree',
            'view_mode': 'tree',
            'res_model': 'purchase.order.line',
            'views': [(compose_form_id, 'tree')],
            'view_id': compose_form_id,
            'target': 'new',
            'context': ctx,
            'domain': [('product_id', '=', self.product_id.id), ('partner_id', '=', self.partner_id.id)],
        }

    @api.multi
    def action_view_quants_by_item(self):
        return self.action_view_quant_by_product_ids([self.product_id.id])

    @api.depends('order_id.picking_ids.state')
    def _compute_qty_returned(self):
        return_move_ids = self.env['stock.move'].search([
            ('origin_returned_move_id.purchase_line_id', 'in', self.ids),
            ('state', '=', 'done'),
            ('location_id.usage', '!=', 'supplier')])
        for line in self:
            if line.order_id.state not in ['purchase', 'done']:
                line.qty_returned = 0.0
                continue
            total = 0.0

            for return_move in return_move_ids:
                if line.id == return_move.origin_returned_move_id.purchase_line_id.id:
                    if return_move.product_uom != line.product_uom:
                        total += return_move.product_uom._compute_quantity(return_move.product_uom_qty, line.product_uom)
                    else:
                        total += return_move.product_uom_qty
            line.qty_returned = total
                        #### EDIT IT BY WALLE CHANGED ORIGIN RETURN GOODS RULE BY BYIT DEMAND
            # for move in line.move_ids:
            #     for return_move in move.returned_move_ids:
            #         if return_move.state == 'done' and return_move.picking_type_id.code == 'outgoing':
            #             if return_move.product_uom != line.product_uom:
            #                 total += return_move.product_uom._compute_quantity(return_move.product_uom_qty, line.product_uom)
            #             else:
            #                 total += return_move.product_uom_qty
